package com.zbkj.crmeb.store.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.PageHelper;
import com.utils.DateUtil;
import com.utils.vo.dateLimitUtilVo;
import com.zbkj.crmeb.store.dao.StoreOrderStatusDao;
import com.zbkj.crmeb.store.model.StoreOrderStatus;
import com.zbkj.crmeb.store.request.StoreOrderStatusSearchRequest;
import com.zbkj.crmeb.store.service.StoreOrderStatusService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
* @author Mr.Zhang
* @description StoreOrderStatusServiceImpl 接口实现
* @date 2020-05-28
*/
@Service
public class StoreOrderStatusServiceImpl extends ServiceImpl<StoreOrderStatusDao, StoreOrderStatus> implements StoreOrderStatusService {

    @Resource
    private StoreOrderStatusDao dao;


    /**
    * 列表
    * @param request 请求参数
    * @param pageParamRequest 分页类参数
    * @author Mr.Zhang
    * @since 2020-05-28
    * @return List<StoreOrderStatus>
    */
    @Override
    public List<StoreOrderStatus> getList(StoreOrderStatusSearchRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());

        //带 StoreOrderStatus 类的多条件查询
        LambdaQueryWrapper<StoreOrderStatus> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        StoreOrderStatus model = new StoreOrderStatus();
        BeanUtils.copyProperties(request, model);
        lambdaQueryWrapper.setEntity(model);
        if(!Objects.equals(request.getOperating(),1)){
            lambdaQueryWrapper.ne(StoreOrderStatus::getChangeType,Constants.ORDER_UPDATE_TAX_AND_FREIGHT);
        }
        if(!Objects.equals(request.getOperating(),0)){
            lambdaQueryWrapper.ne(StoreOrderStatus::getChangeType,Constants.ORDER_PLATFORM_NOTE).ne(StoreOrderStatus::getChangeType,Constants.ORDER_SUPPLIER_LOG_REFUND);
        }
        if(!Objects.equals(request.getOperating(),2)){
            lambdaQueryWrapper.ne(StoreOrderStatus::getChangeType,Constants.ORDER_MERCHANT_NOTE);
        }
        if(Objects.equals(request.getOperating(),2) || Objects.equals(request.getOperating(),3)){
            lambdaQueryWrapper.ne(StoreOrderStatus::getChangeType,Constants.ORDER_STATUS_CACHE_PUSH_ORDER);
        }
        return dao.selectList(lambdaQueryWrapper);
    }

    /**
     * 保存订单退款记录
     * @param orderId Integer 订单号
     * @param amount BigDecimal 金额
     * @author Mr.Zhang
     * @since 2020-05-28
     */
//    @Async("taskExecutor")
    @Override
    public void saveRefund(Integer orderId,String childOrderNumber, BigDecimal amount, String message,boolean status) {
        String str = status ? "退货退款,退款给用户{0}元" : "补偿性退款,退款给用户{0}元";
        String changeMessage = MessageFormat.format(str,amount.toString());
        //此处更新订单状态
//        String changeMessage = Constants.ORDER_LOG_MESSAGE_REFUND_PRICE.replace("{childOrderNumber}", childOrderNumber).replace("{amount}", amount.toString());
        if(StringUtils.isNotBlank(message)){
            changeMessage += message;
        }
        createLog(orderId,childOrderNumber, Constants.ORDER_LOG_REFUND_PRICE, changeMessage);
    }

    /**
     * 创建记录日志
     * @param orderId Integer 订单号
     * @param type String 类型
     * @param message String 消息
     * @author Mr.Zhang
     * @since 2020-05-28
     */
    @Override
    public void createLog(Integer orderId, String type, String message) {
        try{
            StoreOrderStatus storeOrderStatus = new StoreOrderStatus();
            storeOrderStatus.setOid(orderId);
            storeOrderStatus.setChangeType(type);
            storeOrderStatus.setChangeMessage(message);
            storeOrderStatus.setCreateTime(DateUtil.nowDateTime());
            if(!save(storeOrderStatus)){
                throw new CrmebException("保存失败");
            }
        }catch (Exception e){
            throw new CrmebException("日志记录异常： "+e);
        }
    }

    @Override
    public void createLog(Integer orderId,String orderNumber, String type, String message) {
        try{
            StoreOrderStatus storeOrderStatus = new StoreOrderStatus();
            storeOrderStatus.setOid(orderId);
            storeOrderStatus.setOrderNumber(orderNumber);
            storeOrderStatus.setChangeType(type);
            storeOrderStatus.setChangeMessage(message);
            storeOrderStatus.setCreateTime(DateUtil.nowDateTime());
            if(!save(storeOrderStatus)){
                throw new CrmebException("保存失败");
            }
        }catch (Exception e){
            throw new CrmebException("日志记录异常： "+e);
        }
    }

    /**
     * 根据实体获取
     * @param storeOrderStatus 订单状态参数
     * @return 查询结果
     */
    @Override
    public List<StoreOrderStatus> getByEntity(StoreOrderStatus storeOrderStatus) {
        LambdaQueryWrapper<StoreOrderStatus> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.setEntity(storeOrderStatus);
        return dao.selectList(lambdaQueryWrapper);
    }

    @Override
    public String getNote(Integer orderId, String childOrderNumber, String type) {
        StoreOrderStatus orderNote = this.getOne(Wrappers.<StoreOrderStatus>lambdaQuery().eq(StoreOrderStatus::getChangeType, type)
                .eq(StoreOrderStatus::getOid, orderId).eq(StoreOrderStatus::getOrderNumber, childOrderNumber).orderByDesc(StoreOrderStatus::getCreateTime).last("LIMIT 1"));
        if(orderNote == null){
            return null;
        }
        String note = orderNote.getChangeMessage();
        note = note.startsWith("修改备注:") ? note.replaceFirst("修改备注:","") : note.replaceFirst("订单备注:","");
        return note;
    }

    @Override
    public Map<String, String> getNoteMap(List<String> childOrderNoList, String type) {
        List<StoreOrderStatus> list = this.list(Wrappers.<StoreOrderStatus>lambdaQuery().eq(StoreOrderStatus::getChangeType, type)
                .in(StoreOrderStatus::getOrderNumber, childOrderNoList)
                .groupBy(StoreOrderStatus::getOrderNumber).orderByDesc(StoreOrderStatus::getCreateTime));
        list.parallelStream().forEach(e->{
            String note = e.getChangeMessage();
            note = note.startsWith("修改备注:") ? note.replaceFirst("修改备注:","") : note.replaceFirst("订单备注:","");
            e.setChangeMessage(note);
        });
        return list.stream().collect(Collectors.toMap(StoreOrderStatus::getOrderNumber, StoreOrderStatus::getChangeMessage));
    }

    /**
     * 功能描述: 退款订单数
     * @Param: [orderIds, dateLimit]
     * @Return: java.lang.Integer
     * @Author: wangzh
     * @Date: 2023/1/3 17:38
     */
    @Override
    public Integer selectRefundNum(List<Integer> orderIds, dateLimitUtilVo dateLimit) {
        return dao.selectRefundNum(Wrappers.<StoreOrderStatus>lambdaQuery()
                .in(StoreOrderStatus::getOid, orderIds)
                .eq(StoreOrderStatus::getChangeType, "refund_price")
                .between(StoreOrderStatus::getCreateTime, dateLimit.getStartTime(), dateLimit.getEndTime())
                .groupBy(StoreOrderStatus::getOrderNumber));
    }

}

